import { useDynamicList } from 'ahooks';
import { Button, Icon, Input, message, Row } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle } from 'react';

export function toMap(variables) {
  return variables.reduce((acc, { headerName, headerValue }) => {
    if (headerName) {
      acc[headerName] = headerValue;
    }
    return acc;
  }, {});
}

function valueRenderFunction({ disabled, value, onChange }) {
  return (
    <Input
      disabled={disabled}
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder="VALUE"
    />
  );
}

export async function clipboardTextHeaderValues() {
  // eslint-disable-next-line compat/compat
  const text = await navigator.clipboard.readText();
  try {
    const lines = text.split('\n');
    const headers = [];
    lines.forEach(line => {
      const parts = line.split(':');
      if (parts.length !== 2) {
        throw new Error('剪切板内容格式不正确');
      }
      const headerName = parts[0];
      const headerValue = parts[1];
      headers.push({ headerName, headerValue });
    });
    return headers;
  } catch (error) {
    throw new Error('剪切板内容格式不正确');
  }
}

function DynamicHttpHeaders(
  { value = [], onChange, disabled, renderValueComponent = valueRenderFunction },
  ref
) {
  const { list, remove, getKey, replace, push, resetList } = useDynamicList(value || []);

  useEffect(() => {
    onChange(list);
  }, [list, onChange]);

  useImperativeHandle(ref, () => ({
    resetList: value => {
      resetList(value);
    },
  }));

  const Header = (index, item) => (
    <Row
      key={getKey(index)}
      gutter={16}
      style={{ marginBottom: '8px', display: 'flex', alignItems: 'center', paddingLeft: 8 }}
    >
      <div className="margin-right" style={{ flex: 1 }}>
        <Input
          disabled={disabled}
          value={item.headerName}
          onChange={e => replace(index, { ...item, headerName: e.target.value })}
          placeholder="KEY"
        />
      </div>
      <div className="margin-right" style={{ flex: 1 }}>
        {renderValueComponent({
          disabled,
          value: item.headerValue,
          onChange: value => replace(index, { ...item, headerValue: value }),
        })}
      </div>
      <div style={{ flexBasis: 27, display: 'flex', alignItems: 'center' }}>
        <Icon
          style={{
            fontSize: '16.5px',
            color: '#999',
            transition: 'all 0.3s',
          }}
          onClick={() => remove(index)}
          type="minus-circle"
        />
      </div>
    </Row>
  );
  return (
    <>
      {list.map((ele, index) => Header(index, ele))}
      {disabled ? null : (
        <Button type="dashed" block onClick={() => push({})}>
          + 添加
        </Button>
      )}
    </>
  );
}

export default forwardRef(DynamicHttpHeaders);
